package com.voicechat.firstmet.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.DownloadManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.TIMCallBack;
import com.tencent.TIMManager;
import com.voicechat.firstmet.App;
import com.voicechat.firstmet.BuildConfig;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.LoginActivity;
import com.voicechat.firstmet.bean.CropBean;
import com.voicechat.firstmet.client.WsManager;
import com.voicechat.firstmet.imcontrol.LoginHelper;
import com.voicechat.firstmet.imcontrol.MessageEvent;
import com.voicechat.firstmet.realm.GiftDataBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;


/**
 * 创建时间：2017/06/04
 * 创建者: taoyong
 * 模块描述：通用工具类
 */
public class Utils {
    public static int[] LABELCOLOR = {0xffFFACAC,0xffC180FA,0xff3AE5C9,0xffFE9292,
            0xff7CB2F1,0xffFFCD80};
    private Utils() {
    }
    private static final String TAG = "Utils";
    private static DisplayMetrics displayMetrics = null;

    /**
     * 获取当前屏幕宽度(px)
     *
     * @param context
     * @return
     */
    public static int getSrecchWidth(Context context) {
        if (displayMetrics == null) {
            displayMetrics = context.getResources().getDisplayMetrics();
        }
        return displayMetrics.widthPixels;
    }

    /**
     * 获取当前屏幕高度(px)
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        if (displayMetrics == null) {
            displayMetrics = context.getResources().getDisplayMetrics();
        }
        return displayMetrics.heightPixels;
    }


    /**
     * 改变textview指定位置字体颜色
     *
     * @param textView
     * @param start
     * @param end
     * @param color
     */
    public void setText(TextView textView, int start, int end, String color) {
        SpannableString spannableString = new SpannableString(textView.getText().toString());  //获取按钮上的文字
        ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor(color));
        spannableString.setSpan(span, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);//将倒计时的时间设置为红色
        textView.setText(spannableString);
    }

    /**
     * 获取设备的状态栏高度(px)
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        try {
            //获取status_bar_height资源的ID . 可能报NullPointerException
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                //根据资源ID获取响应的尺寸值
                return context.getResources().getDimensionPixelSize(resourceId);
            }
            return -1;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * TOKEN过期，强制下线
     */
    public static void setToken(Context context) {
        Log.i(TAG, "setToken: ---------" + LoginHelper.newInstance().isLogin());
        if (LoginHelper.newInstance().isLogin()) {
            //登出
            TIMManager.getInstance().logout(new TIMCallBack() {
                @Override
                public void onError(int code, String desc) {
                    Log.i(TAG, "onError: ----code------" + code);
                    //toast_MakeText("登录错误，请重新登录",context);
                    //登出成功
                    SPUtils.setEditorKeyValue(SPUtils.SP_USERSIG, "");
                    SPUtils.setEditorKeyValue(SPUtils.SP_TOKEN, "");
                    SPUtils.setEditorKeyValue(SPUtils.SP_MYSELFINFO, "");
                    SPUtils.setEditorKeyValue(SPUtils.SP_PHONE,"");
                    MessageEvent.getInstance().clear();
                    DataCleanManager.clearAllCache(context);//清楚缓存
                    WsManager.getInstance(context).disconnect();//断开长链接
                    context.startActivity(new Intent(context, LoginActivity.class));
                    App.getInstance().removeAllActivity_();
                }
                @Override
                public void onSuccess() {
                    Log.i(TAG, "onSuccess: ----------");
                    // toast_MakeText("登录错误，请重新登录",context);
                    //登出成功
                    SPUtils.setEditorKeyValue(SPUtils.SP_USERSIG, "");
                    SPUtils.setEditorKeyValue(SPUtils.SP_TOKEN, "");
                    SPUtils.setEditorKeyValue(SPUtils.SP_MYSELFINFO, "");
                    SPUtils.setEditorKeyValue(SPUtils.SP_PHONE,"");
                    DataCleanManager.clearAllCache(context);//清楚缓存
                    MessageEvent.getInstance().clear();
                    WsManager.getInstance(context).disconnect();//断开长链接
                    context.startActivity(new Intent(context, LoginActivity.class));
                    App.getInstance().removeAllActivity_();
                }
            });
        } else {
            //登出成功
            SPUtils.setEditorKeyValue(SPUtils.SP_USERSIG, "");
            SPUtils.setEditorKeyValue(SPUtils.SP_TOKEN, "");
            SPUtils.setEditorKeyValue(SPUtils.SP_MYSELFINFO, "");
            SPUtils.setEditorKeyValue(SPUtils.SP_PHONE,"");
            DataCleanManager.clearAllCache(context);//清楚缓存
            MessageEvent.getInstance().clear();
            WsManager.getInstance(context).disconnect();//断开长链接
            context.startActivity(new Intent(context, LoginActivity.class));
            App.getInstance().removeAllActivity_();
        }
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static final boolean isOPen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    /**
     * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指
     * 定精度，以后的数字四舍五入。
     *
     * @param v1    被除数
     * @param v2    除数
     * @param scale 表示表示需要精确到小数点以后几位。
     * @return 两个参数的商
     */
    public static double div(double v1, double v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     *
     * @param context
     * @param pxValue （DisplayMetrics类中属性density）
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        if (displayMetrics == null) {
            displayMetrics = context.getResources().getDisplayMetrics();
        }
        final float scale = displayMetrics.density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param context
     * @param dipValue （DisplayMetrics类中属性density）
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        if (displayMetrics == null) {
            displayMetrics = context.getResources().getDisplayMetrics();
        }
        final float scale = displayMetrics.density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param context
     * @param pxValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        if (displayMetrics == null) {
            displayMetrics = context.getResources().getDisplayMetrics();
        }
        final float fontScale = displayMetrics.scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param context
     * @param spValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        if (displayMetrics == null) {
            displayMetrics = context.getResources().getDisplayMetrics();
        }
        final float fontScale = displayMetrics.scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 得到指定格式的时间
     *
     * @param time   时间
     * @param format 格式
     * @return 指定格式的时间
     */
    public static String getTime(long time, String format) {
        return new SimpleDateFormat(format).format(time);
    }

    /**
     * 创建一个Gson对象
     */
    private static Gson gson = null;

    /**
     * 通用解析json的方法
     *
     * @param jsonResult json数据
     * @param cls        实体-对象
     * @param <T>        泛型
     * @return 返回的实体对象
     */
    public static <T> T jsonBean(String jsonResult, Class<T> cls) {
        if (gson == null) {
            gson = new GsonBuilder().disableHtmlEscaping().create();
//            gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
        }
        T t = gson.fromJson(jsonResult, cls);
        return t;
    }

    /**
     * 通用实体转JSON方法
     *
     * @param object 实体
     * @return String类型JSON数据
     */
    public static String toJson(Object object) {
        if (gson == null) {
            gson = new GsonBuilder().disableHtmlEscaping().create();
//            gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
        }
//        String oldStr = object.toString();
        String newStr = gson.toJson(object);
//        Log.i("toJson", "oldStr:" + oldStr);
//        Log.i("toJson", "newStr:" + newStr);
        return newStr;
    }

    /**
     * 解析 ResponseInfo<T> 对应实体的专用方法
     *
     * @param jsonResult json数据
     * @param cls        实体-对象
     * @param <T>        泛型
     * @return 返回的实体对象(ResponseInfo < T >)
     */
    public static <T> GiftDataBean<T> getResponse$T(String jsonResult, Class<T> cls) {
        if (gson == null) {
            gson = new Gson();
        }
        GiftDataBean<T> info = new GiftDataBean<>();
        try {
            JSONObject obj = new JSONObject(jsonResult);
            if (obj.has("code"))
                info.setCode(obj.getInt("code"));
            if (obj.has("msg"))
                info.setMsg(obj.getString("msg"));
            if (obj.has("version"))
                info.setVersion(obj.getString("version"));
            if (obj.has("list")) {
                JSONArray param = obj.getJSONArray("list");
                int count = param == null ? 0 : param.length();
                if (count > 0) {
                    List<T> list = new ArrayList<>();
                    for (int i = 0; i < count; i++) {
                        list.add(gson.fromJson(param.get(i).toString(), cls));
                    }
                    info.setList(list);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }


    /**
     * 以逗号分隔图片地址
     *
     * @param str
     * @return
     */
    public static String[] convertStrToArray(String str) {
        String[] strArray = null;
        strArray = str.split(","); //拆分字符为"," ,然后把结果交给数组strArray
        return strArray;
    }

    /**
     * 时间戳转换
     *
     * @param unixTime
     * @param format
     * @return
     */
    public static String formatUnixTime(long unixTime, String format) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        Date date = new Date(unixTime * 1000);
        return dateFormat.format(date);
    }

    /**
     * 调此方法输入所要转换的时间输入例如（"2014-06-14-16-09-00"）返回时间戳
     *
     * @param time
     * @return
     */
    public static String dataOne(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss",
                Locale.CHINA);
        Date date;
        String times = null;
        try {
            date = sdr.parse(time);
            long l = date.getTime();
            String stf = String.valueOf(l);
            times = stf.substring(0, 10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return times;
    }

    /**
     * 判断是否为今天(效率比较高)
     *
     * @param day 传入的 时间  "2016-06-28 10:10:30" "2016-06-28" 都可以
     * @return true今天 false不是
     * @throws ParseException
     */
    public static boolean IsToday(String day) throws ParseException {
        Calendar pre = Calendar.getInstance();
        Date predate = new Date(System.currentTimeMillis());
        pre.setTime(predate);
        Calendar cal = Calendar.getInstance();
        Date date = getDateFormat().parse(day);
        cal.setTime(date);
        if (cal.get(Calendar.YEAR) == (pre.get(Calendar.YEAR))) {
            int diffDay = cal.get(Calendar.DAY_OF_YEAR)
                    - pre.get(Calendar.DAY_OF_YEAR);
            if (diffDay == 0) {
                return true;
            }
        }
        return false;
    }

    public static SimpleDateFormat getDateFormat() {
        if (null == DateLocal.get()) {
            DateLocal.set(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA));
        }
        return DateLocal.get();
    }

    private static ThreadLocal<SimpleDateFormat> DateLocal = new ThreadLocal<>();

    /**
     * @param t 输入后台传递过来的秒为单位的时间
     * @return 返回 朋友圈评论中所要求的时间  不超过一天为几时几分 超过一天为几月几日几时几分  超过一年为几年几月几日几时几分
     */
    public static String getCommentDate(long t) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        Date date = new Date(t * 1000);
        String time = dateFormat.format(date);
        String[] times = time.split("-");

        Date date1 = new Date(System.currentTimeMillis());
        String time1 = dateFormat.format(date1);
        String[] times1 = time1.split("-");

        if (Integer.parseInt(times[0]) == Integer.parseInt(times1[0])) {//说明是今年
            if (Integer.parseInt(times[1]) == Integer.parseInt(times1[1]) && Integer.parseInt(times[2]) == Integer.parseInt(times1[2])) {//同一天
                SimpleDateFormat dateFormatDay = new SimpleDateFormat("HH:mm");
                String timeDay = dateFormatDay.format(date);
                return timeDay;
            } else {//不是同一天
                SimpleDateFormat dateFormatMonth = new SimpleDateFormat("MM月dd日 HH:mm");
                String timeMonth = dateFormatMonth.format(date);
                return timeMonth;
            }
        } else if (Integer.parseInt(times[0]) < Integer.parseInt(times1[0])) {//说明是前几年
            SimpleDateFormat dateFormatYear = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
            String timeYear = dateFormatYear.format(date);
            return timeYear;
        }

        return null;
    }

    /**
     * 将时间戳转为代表"距现在多久之前"的字符串
     *
     * @param
     * @return
     */
    public static String getStandardDate(long t) {
        StringBuffer sb = new StringBuffer();
        String date = Utils.formatUnixTime(t, "yyyy年MM月dd日");
//        long t = Long.parseLong(timeStr);
        long time = System.currentTimeMillis() - (t * 1000);
        long mill = (long) Math.floor(time / 1000);//秒前
        long minute = (long) Math.floor(time / 60 / 1000.0f);// 分钟前
        long hour = (long) Math.floor(time / 60 / 60 / 1000.0f);// 小时
//        long day = (long) Math.floor(time / 24 / 60 / 60 / 1000.0f);// 天前
        long day = hour / 24;
//        Log.i(TAG, "getStandardDate: ---minute---"+minute+"--------mill/60--------"+mill/60);
        if (day - 1 > 0) {
            if (day > 5) {
                sb.append(date);
            } else {
                sb.append(day + "天前");
            }
//            sb.append(date);
        } else if (hour - 1 > 0) {
            if (hour >= 24) {
                sb.append(day + "天前");
            } else {
                sb.append(hour + "小时前");
            }
        } else if (minute - 1 > 0) {
            if (minute >= 60) {
                sb.append(hour + "小时前");
            } else {
                sb.append(minute + "分钟前");
            }
        } else if (mill - 1 > 0) {
            if (mill >= 60) {
                sb.append(minute + "分钟前");
            } else {
                sb.append(mill + "秒前");
            }
        } else {
            sb.append("刚刚");
        }
        /*if (!sb.toString().equals("刚刚")) {
            sb.append("前");
        }*/
        return sb.toString();
    }

    /**
     * 将时间转为代表"距现在多久之前"的字符串
     *
     * @param
     * @return
     */
    public static String getStandardDate(String date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("MM月dd日");
        Date date1 = null;
        try {
            date1 = simpleDateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String format = simpleDateFormat2.format(date1);
         //Log.i(TAG, "getStandardDate: -----------"+simpleDateFormat.format(date1));
        //Log.i(TAG, "getStandardDate: -----------"+simpleDateFormat.format(date1));
        StringBuffer sb = new StringBuffer();
        long t = 0;
        try {
            t = parseDateToLong(date);//将string时间转为时间戳
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //String format = DateTimeUtil.strFormatStr(date);
        long time = System.currentTimeMillis() - t;
        long mill = (long) Math.floor(time / 1000);//秒前
        long minute = (long) Math.floor(time / 60 / 1000.0f);// 分钟前
        long hour = (long) Math.floor(time / 60 / 60 / 1000.0f);// 小时
//        long day = (long) Math.floor(time / 24 / 60 / 60 / 1000.0f);// 天前
        long day = hour / 24;
        try {
            if (getIsCurYearFromTime(stringToDate(date, "yyyy-MM-dd HH:mm:ss"))) {
                if (day - 1 > 0) {
                    if (day > 5) {
                        sb.append(format);
                    } else {
                        sb.append(day + "天前");
                    }
                    //            sb.append(date);
                } else if (hour - 1 > 0) {
                    if (hour >= 24) {
                        sb.append(day + "天前");
                    } else {
                        sb.append(hour + "小时前");
                    }
                } else if (minute - 1 > 0) {
                    if (minute >= 60) {
                        sb.append(hour + "小时前");
                    } else {
                        sb.append(minute + "分钟前");
                    }
                } else if (mill - 1 > 0) {
                    if (mill >= 60) {
                        sb.append(minute + "分钟前");
                    } else {
                        sb.append(mill + "秒前");
                    }
                } else {
                    sb.append("刚刚");
                }
            } else {
                sb.append(Utils.formatUnixTime(t/1000, "yyyy年MM月dd日"));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        /*if (!sb.toString().equals("刚刚")) {
            sb.append("前");
        }*/
        return sb.toString();
    }

    /**
     * 评论时间格式
     *
     * @param t
     * @return
     */
    public static String getStandardDateComment(long t) {
        StringBuffer sb = new StringBuffer();
        String date = Utils.formatUnixTime(t, "MM月dd日");
        String time1 = Utils.formatUnixTime(t, "HH:mm");
//        long t = Long.parseLong(timeStr);
        long time = System.currentTimeMillis() - (t * 1000);
        long mill = (long) Math.ceil(time / 1000);//秒前
        long minute = (long) Math.ceil(time / 60 / 1000.0f);// 分钟前
        long hour = (long) Math.ceil(time / 60 / 60 / 1000.0f);// 小时
        long day = (long) Math.ceil(time / 24 / 60 / 60 / 1000.0f);// 天前
        if (day - 1 > 0) {
            sb.append(time1);
        } else {
            sb.append(date + " " + time1);
        }
        return sb.toString();
    }

    /**
     * 新版社区将时间戳转为代表"距现在多久之前"的字符串
     * {需求，分钟前，小时前，天前，超过五天显示}
     *
     * @param
     * @return
     */
    public static String getCircleListDate(long t) {
        Log.i(TAG, "getCircleListDate: =====时间======" + t);
        StringBuffer sb = new StringBuffer();
        String date = Utils.formatUnixTime(t, "MM月dd日");
        long time = System.currentTimeMillis() - (t * 1000);
        long mill = (long) Math.floor(time / 1000);//秒前
        long minute = (long) Math.floor(time / 60 / 1000.0f);// 分钟前
        long hour = (long) Math.floor(time / 60 / 60 / 1000.0f);// 小时
        long day = hour / 24;
        if (getIsCurYearFromTime(t)) {
            if (day - 1 > 0) {
                if (day > 5) {
                    sb.append(date);
                } else {
                    sb.append(day + "天前");
                }
            } else if (hour - 1 > 0) {
                if (hour >= 24) {
                    sb.append(day + "天前");
                } else {
                    sb.append(hour + "小时前");
                }
            } else if (minute - 1 > 0) {
                if (minute >= 60) {
                    sb.append(hour + "小时前");
                } else {
                    sb.append(minute + "分钟前");
                }
            } else if (mill - 1 > 0) {
                if (mill >= 60) {
                    sb.append(minute + "分钟前");
                } else {
                    sb.append(mill + "秒前");
                }
            } else {
                sb.append("刚刚");
            }
        } else {
            sb.append(Utils.formatUnixTime(t, "yyyy年MM月dd日"));
        }

        return sb.toString();
    }

    /**
     * @return
     * @method
     * @description 判断是否是今年
     * @date: 2018/11/17 15:10
     * @author: ljp
     */
    public static boolean getIsCurYearFromTime(long time) {
        String date = Utils.formatUnixTime(time, "yyyy");
        int tYear = Integer.parseInt(date);
        Calendar a = Calendar.getInstance();
        int curYear = a.get(Calendar.YEAR);
        return tYear == curYear;
    }

    /**
     * @return
     * @method
     * @description 判断是否是今年
     * @date: 2018/11/17 15:10
     * @author: ljp
     */
    public static boolean getIsCurYearFromTime(Date time) {
        String date = dateToString(time, "yyyy");
        int tYear = Integer.parseInt(date);
        Calendar a = Calendar.getInstance();
        int curYear = a.get(Calendar.YEAR);
        return tYear == curYear;
    }

    /**
     * {将时间戳例"2001-03-15 15-37-05"转为毫秒数}
     *
     * @param date 24时制时间戳例"2001-03-15 15:37:05"
     * @return
     * @throws ParseException
     */
    public static long parseDateToLong(String date) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制
//      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");//12小时制
        long time = simpleDateFormat.parse(date).getTime();
        return time;
    }

    //可根据需要自行截取数据显示
    public static String getStringTime(Date date) {
        // Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy");
        return format.format(date);
    }

    /**
     * 创建一个ContentValues对象
     */
    private static ContentValues contentValues = null;

    /**
     * 返回一个ContentValues对象
     *
     * @return ContentValues对象
     */
    public static ContentValues getContentValues() {
        if (contentValues == null) {
            contentValues = new ContentValues();
        } else {
            contentValues.clear();
        }
        return contentValues;
    }

    /**
     * 创建一个null的map集合
     */
    private static Map<String, String> map = null;

    /**
     * 得到一个map集合
     *
     * @return map
     */
    public static Map<String, String> getHashMap() {
        if (map == null) {
            map = new HashMap<>();
        } else {
            map.clear();
        }
        map.put("token", SPUtils.getEditoString(SPUtils.SP_TOKEN));
        Log.d("token", "getHashMap: " + SPUtils.getEditoString(SPUtils.SP_TOKEN));
        return map;
    }

    /**
     * 网络判断参数
     */
    private static boolean flag = false;

    /**
     * 判断网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean judgeWhetherNet(Context context) {
        flag = NetWorkUtils.isMobileConnected(context);//判断WIFI网络是否可用
        if (!flag) {//如果不可用，继续 判断是否有网络连接
            flag = NetWorkUtils.isNetworkConnected(context);//判断是否有网络连接
        }
        return flag;
    }

    /**
     * 计算两点之间的距离
     *
     * @param x1 起始X坐标
     * @param x2 结束X坐标
     * @param y1 起始Y坐标
     * @param y2 结束Y坐标
     * @return
     */
    public static double getDistance(double x1, double x2, double y1, double y2) {
        return (Math.sqrt(Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2)));
    }

    /**
     * 计算两点之间的距离
     *
     * @param x1 起始X坐标
     * @param x2 结束X坐标
     * @param y1 起始Y坐标
     * @param y2 结束Y坐标
     * @return
     */
    public static double getDistance_mo(double x1, double x2, double y1, double y2) {
        return (Math.sqrt(Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2))) / 1000;
    }

    private static DecimalFormat df;

    /**
     * string类型转换为两位
     *
     * @return
     */
    public static String stringTurn2double(String f) {
        if (f != null && !"".equals(f)) {
            if (null == df) {
                df = new DecimalFormat("0.00");
            }
            return df.format(Double.parseDouble(f));
        }
        return "";
    }

    /**
     * double类型转换为两位
     *
     * @return
     */
    public static String doubleTurn2double(double f) {
        if (null == df) {
            df = new DecimalFormat("0.00");
        }
        return df.format(f);
    }

    /**
     * 生成透明背景的圆形图片,！注意要生成透明背景的圆形，图片一定要png类型的，不能是jpg类型
     *
     * @param bitmap
     * @return
     */
    public static Bitmap getCircleBitmap(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        try {
            Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(),
                    bitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(circleBitmap);
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight()));
            float roundPx = 0.0f;
            // 以较短的边为标准
            if (bitmap.getWidth() > bitmap.getHeight()) {
                roundPx = bitmap.getHeight() / 2.0f;
            } else {
                roundPx = bitmap.getWidth() / 2.0f;
            }
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(Color.WHITE);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            final Rect src = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            canvas.drawBitmap(bitmap, src, rect, paint);
            return circleBitmap;
        } catch (Exception e) {
            return bitmap;
        }
    }

    /**
     * 验证手机号码是否错误
     *
     * @param mobiles 手机号码
     * @return 手机号码是否是否正确（true---正确，false---错误的）
     */
    public static boolean isMobileNO(String mobiles) {
                    /*
                        移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
                        联通：130、131、132、152、155、156、185、186
                        电信：133、153、180、189、（1349卫通）
                        总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
                    */
        String telRegex = "[1][345789]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、4、5、7、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles))
            return false;
        else
            return mobiles.matches(telRegex);
    }

    /**
     * @return
     * @method
     * @description 身份证号码验证
     * @date: 2018/11/6 10:13
     * @author: ljp
     */
    public static boolean isCardNumber(String cardNum) {
        /**
         * 正则表达式:验证身份证
         */
        String REGEX_ID_CARD = "(^\\d{15}$)|(^\\d{17}([0-9]|X)$)";
        if (TextUtils.isEmpty(cardNum))
            return false;
        else
            return cardNum.matches(REGEX_ID_CARD);
    }

    /**
     * 验证电子邮件是否错误
     *
     * @param email
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isEmail(String email) {
        //电子邮件
        //  String regex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        //  String regex = "^([a-z0-9A-Z]+[-|_|\\\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\\\.)+[a-zA-Z]{2,}$";
        String regex = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";

        return Pattern.matches(regex, email);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    public static boolean isShouldHideInputView(View v, MotionEvent event) {
        if (v != null && (v instanceof View)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     *
     * @param token
     */
    public static void hideSoftInput(IBinder token, Context context) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * @return
     * @method
     * @description 弹出软件盘
     * @date: 2018/11/2 15:28
     * @author: ljp
     */
    public static void showKeyboard(Activity context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

    }

    /**
     * 获得版本号信息
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {

        PackageManager pm = context.getPackageManager();

        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 版本的代码
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {

        PackageManager pm = context.getPackageManager();

        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }

    private static Map<String, int[]> cardstyleMaps = null;


    public static String getToken() {
        return SPUtils.getEditoString(SPUtils.SP_TOKEN);
    }

    public static String getPhone() {
        return SPUtils.getEditoString(SPUtils.SP_PHONE);
    }


    public static String getResult(String response) throws JSONException {
        JSONObject json = new JSONObject(response);
        String result = json.getString("result");
        return result;
    }

    /* */

    /**
     * 账户冻结，强制下线
     *//*
    public static void setToken(Context context) {
        RongIM.getInstance().logout();
        //SPUtils.clearEditorKeyValue();
        SPUtils.setEditorKeyValue(SPUtils.SP_TOKENID, "");
        SPUtils.setEditorKeyValue(SPUtils.SP_TOKEN, "");
        SPUtils1.put(context, "isWiFi", 1);
        SPUtils.setEditorKeyValue("checked", false);
        CleanManagerUtils.clearAllCache(context);
        context.startActivity(new Intent(context, LARLoginActivity.class));
        App.getInstance().removeAllActivity_();
    }
*/
    public static void toast_MakeText(String s, Context context) {
        if (TextUtils.isEmpty(s)) {
            Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * @param context
     * @param charSequence   监听到的文本onTextChanged(CharSequence charSequence
     * @param editText       文本框视图
     * @param max            最大转账金额
     * @param DECIMAL_DIGITS 限制保留小数点后几位
     */
    // TODO: 2017/9/22 限制转账输入框不能以0开头，并设置输入小数点后的位数
    public static void setTransferInputType(Context context, CharSequence charSequence, EditText editText, int max, String toast, int DECIMAL_DIGITS) {
        //保留小数点后两位
        if (charSequence.toString().contains(".")) {
            if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > DECIMAL_DIGITS) {
                charSequence = charSequence.toString().subSequence(0,
                        charSequence.toString().indexOf(".") + DECIMAL_DIGITS + 1);
                editText.setText(charSequence);
                editText.setSelection(charSequence.length());
            }
        }
        //自动补0
        if (charSequence.toString().trim().substring(0).equals(".")) {
            charSequence = "0" + charSequence;
            editText.setText(charSequence);
            editText.setSelection(2);
        }
        //设置不能连续输入0
        if (charSequence.toString().startsWith("0")
                && charSequence.toString().trim().length() > 1) {
            if (!charSequence.toString().substring(1, 2).equals(".")) {
                editText.setText(charSequence.subSequence(0, 1));
                editText.setSelection(1);
                return;
            }
        }
        //设置不超过max
        if (!TextUtils.isEmpty(charSequence.toString().trim()) && Double.valueOf(charSequence.toString().trim()) > max) {
            Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
            String s = String.valueOf(max);
            editText.setText(s);
            editText.setSelection(s.length());
            return;
        }
    }

    /**
     * @param context
     * @param charSequence   监听到的文本onTextChanged(CharSequence charSequence
     * @param editText       文本框视图
     * @param max            最大转账金额
     * @param DECIMAL_DIGITS 限制保留小数点后几位
     */
    public static void setTransferInputTypeD(Context context, CharSequence charSequence, EditText editText, double max, String toast, int DECIMAL_DIGITS) {
        if (charSequence.toString().contains(".")) {
            if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > DECIMAL_DIGITS) {
                charSequence = charSequence.toString().subSequence(0,
                        charSequence.toString().indexOf(".") + DECIMAL_DIGITS + 1);
                editText.setText(charSequence);
                editText.setSelection(charSequence.length());
            }
        }
        if (charSequence.toString().trim().substring(0).equals(".")) {
            charSequence = "0" + charSequence;
            editText.setText(charSequence);
            editText.setSelection(2);
        }
        if (charSequence.toString().startsWith("0")
                && charSequence.toString().trim().length() > 1) {
            if (!charSequence.toString().substring(1, 2).equals(".")) {
                editText.setText(charSequence.subSequence(0, 1));
                editText.setSelection(1);
                return;
            }
        }
        //设置不超过max
        if (!TextUtils.isEmpty(charSequence.toString().trim()) && Double.valueOf(charSequence.toString().trim()) > max) {
            if (!TextUtils.isEmpty(toast)) {
                Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
            }
            String s = String.valueOf(max);
            editText.setText(s);
            editText.setSelection(s.length());
            return;
        }

    }

    /**
     * @param d
     * @return
     */
    // TODO: 2017/10/16 保留小数点后两位
    public static String formatD2(double d) {
        String ret = String.format("%.2f", d);
        return ret;
    }

    public static String formatD2(float f) {
        String ret = String.format("%.2f", f);
        return ret;
    }

    public static String formatD2(String strNumber) {
        double parseDouble = Double.parseDouble(strNumber);
        String ret = String.format("%.2f", parseDouble);
        return ret;
    }

    // TODO: 2017/10/16 保留小数点后三位
    public static String formatD3(double d) {
        String ret = String.format("%.3f", d);
        return ret;
    }

    public static String formatD3(String strNumber) {
        double parseDouble = Double.parseDouble(strNumber);
        String ret = String.format("%.3f", parseDouble);
        return ret;
    }

    /* */

    /**
     * @return 加密后的结果
     *//*
    // TODO: 2017/9/28 加密
    public static String encrypt(String json, Context context) {
        String data = null;
        PublicKey publicKey = null;
        try {
            InputStream in = context.getResources().getAssets().open("rsa_public_key.pem");
            publicKey = RSAUtils.loadPublicKey(in);
            RSAUtils.printPublicKeyInfo(publicKey);
            byte[] en = RSAUtils.encryptData(json.getBytes(), publicKey);
            data = Base64Utils.encode(en);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
*/
    public static String subStringF(String string) {
        int length = string.length();
        String substring = string.substring(length - 4, length);
        return substring;
    }


    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri
                .getAuthority());
    }

    public static String getDataColumn(Context context, Uri uri,
                                       String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri
                .getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri
                .getAuthority());
    }

    /*
     *//*更新版本*//*
    public static void updateAppVersion(final Activity activity_imessage) {
        try {
            View view = View.inflate(activity_imessage, R.layout.pop_updateversion, null);
            PopUtils.showPopupWindow(activity_imessage, view, false);
            //版本名称号描述保存到sp
            String versionName = SPUtils.getEditoString("VersionName");
            //版本描述保存到sp
            String versionInfo = SPUtils.getEditoString("VersionInfo");

            TextView tv_versionnumber = (TextView) view.findViewById(R.id.tv_versionnumber);

            LinearLayout ll_content = (LinearLayout) view.findViewById(R.id.ll_content);
            Logger.i(TAG, "versionInfo" + versionInfo + "");
            //动态添加版本更新的描述内容
            try {
                if (versionInfo != null && versionInfo.split("。").length != 0) {
                    String[] split = versionInfo.split("。");
                    Logger.i(TAG, split.length);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    for (int i = 0; i < split.length; i++) {
                        TextView mTv = new TextView(activity_imessage);
                        mTv.setLayoutParams(params);
                        mTv.setLineSpacing(1.2f, 1.2f);//设置行间距
                        mTv.setTextColor(activity_imessage.getResources().getColor(R.color.color666666));
                        mTv.setTextSize(px2sp(activity_imessage, activity_imessage.getResources().getDimensionPixelSize(R.dimen.x54)));
                        mTv.setText(split[i]);
                        if (i == split.length - 1) {
                            mTv.setPadding(0, 0, 0, dip2px(activity_imessage, activity_imessage.getResources().getDimensionPixelSize(R.dimen.y30)));
                        }
                        if (i == 0) {
                            mTv.setPadding(0, dip2px(activity_imessage, activity_imessage.getResources().getDimensionPixelSize(R.dimen.y10)), 0, 0);
                        }
                        ll_content.addView(mTv, i, params);
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            tv_versionnumber.setText(versionName + "上线");

            view.findViewById(R.id.iv_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    PopUtils.hidePopupWindow();
                }
            });
            //立即更新
            view.findViewById(R.id.tv_update).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    PopUtils.hidePopupWindow();
                    setIgnoreVersion(activity_imessage);
                }
            });

            view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    PopUtils.hidePopupWindow();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    /*版本的更新安装*/
    public static void setIgnoreVersion(final Context context) {
        try {
            Intent install = new Intent(Intent.ACTION_VIEW);
            File apkFile = queryDownloadedApk(context);
            install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(install);
        } catch (Exception e) {
            toast_MakeText("安装包有缺失，请退出之后重新下载！！", context);
            /*如果·安装包有缺少，不能安装，删除安装包重新下载*/
            File mFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + "yy" + SPUtils.getEditoString("VersionName") + ".apk");
            if (mFile != null && mFile.isFile() && mFile.exists()) {
                mFile.delete();
            }
            //54217347 54217347
            for (int i = 0; i < 20; i++) {
                File mFile1 = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + "yy" + SPUtils.getEditoString("VersionName") + "(" + i + ").apk");
                File mFile2 = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + "yy" + SPUtils.getEditoString("VersionName") + "-" + i + ".apk");
                if (mFile1 != null && mFile1.isFile() && mFile1.exists()) {
                    mFile1.delete();
                }
                if (mFile2 != null && mFile2.isFile() && mFile2.exists()) {
                    mFile2.delete();
                }
            }
            e.printStackTrace();
        }

    }
    //通过downLoadId查询下载的apk，解决6.0以后安装的问题
    public static File queryDownloadedApk(Context context) {
        File targetApkFile = null;
        DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        SharedPreferences sPreferences = context.getSharedPreferences("downloadcomplete", 0);
        long refernece = sPreferences.getLong("refernece", 0);
        if (refernece != -1) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(refernece);
            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
            Cursor cur = downloader.query(query);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    if (!TextUtils.isEmpty(uriString)) {
                        targetApkFile = new File(Uri.parse(uriString).getPath());
                    }
                }
                cur.close();
            }
        }
        return targetApkFile;
    }

    /*判断下载管理器是否启用*/
    public static boolean isDownloadManagerAvailable(Context context) {
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD
                    || context.getPackageManager()
                    .getApplicationEnabledSetting(
                            "com.android.providers.downloads") == context
                    .getPackageManager().COMPONENT_ENABLED_STATE_DISABLED_USER
                    || context.getPackageManager()
                    .getApplicationEnabledSetting(
                            "com.android.providers.downloads") == context
                    .getPackageManager().COMPONENT_ENABLED_STATE_DISABLED
                    || context.getPackageManager()
                    .getApplicationEnabledSetting(
                            "com.android.providers.downloads") == context
                    .getPackageManager().COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {

                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 判断是否为空
     *
     * @param text
     * @return
     */
    public static boolean isNullOrEmpty(String text) {
        if (text == null || "".equals(text.trim()) || text.trim().length() == 0
                || "null".equals(text.trim())) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * @param phoneNum 手机号
     * @return 匹配结果
     * {匹配手机号，以前三为号段为判断标准}
     * {已开通号段：130-139，145，147，149，150-159，170，171，175-178，180-189，198，199}
     */
    public static boolean matchPhoneNumber(String phoneNum) {
        boolean ret = false;
        String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-9])|(17[0,1,5-8])|(18[0-9])|(19[8,9]))\\d{8}$";
        Pattern pattern = Pattern.compile(regExp);
        Matcher matcher = pattern.matcher(phoneNum);
        ret = matcher.matches();
        return ret;
    }

    /**
     * 限制edittext 不能输入中文
     *
     * @param editText
     */
    public static void setEdNoChinaese(final EditText editText) {
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String txt = s.toString();
                //注意返回值是char数组
                char[] stringArr = txt.toCharArray();
                for (int i = 0; i < stringArr.length; i++) {
                    //转化为string
                    String value = new String(String.valueOf(stringArr[i]));
                    Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
                    Matcher m = p.matcher(value);
                    if (m.matches()) {
                        editText.setText(editText.getText().toString().substring(0, editText.getText().toString().length() - 1));
                        editText.setSelection(editText.getText().toString().length());
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        editText.addTextChangedListener(textWatcher);
    }

    /**
     * 清除WebView缓存
     */
    public static void clearWebViewCache(final Context context) {

        //清理Webview缓存数据库
        try {
            context.deleteDatabase("webview.db");
            context.deleteDatabase("webviewCache.db");
//
//        //WebView 缓存文件
//        File appCacheDir = new File(context.getFilesDir().getAbsolutePath()+  ConstantSet.APP_CACAHE_DIRNAME);
//        Log.e(TAG, "appCacheDir path="+appCacheDir.getAbsolutePath());
//
//        File webviewCacheDir = new File(context.getCacheDir().getAbsolutePath()+"/webviewCache");
//        Log.e(TAG, "webviewCacheDir path="+webviewCacheDir.getAbsolutePath());
//
//        //删除webview 缓存目录
//        if(webviewCacheDir.exists()){
//            deleteFile(webviewCacheDir);
//        }
//        //删除webview 缓存 缓存目录
//        if(appCacheDir.exists()){
//            deleteFile(appCacheDir);
//        }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public static void deleteFile(File file) {

        Log.i(TAG, "delete file path=" + file.getAbsolutePath());

        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            Log.e(TAG, "delete file no exists " + file.getAbsolutePath());
        }
    }

    /**
     * 时间戳 格式转 xx月xx日 x午xx:xx
     *
     * @param time
     */
    public static String transformTime(long time) {
        Date date = new Date(time * 1000L);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.CHINA);
        String timestr = dateFormat.format(date);
        String[] times = timestr.split("-");
        StringBuffer sb = new StringBuffer();
        sb.append(times[1] + "月");
        sb.append(times[2] + "日 ");
        int hour = Integer.parseInt(times[3]);
        sb.append(getTimeDivide(hour));
        sb.append((hour > 12 ? (hour - 12) : hour) + ":");
        sb.append(times[4]);
        //Log.d("Linfo", "transformTime: " + sb.toString());
        return sb.toString();
    }

    /**
     * 时间划分
     * 凌晨:3:00--6:00
     * 早晨:6:00---8:00
     * 上午:8:00--11:00
     * 中午:11:00--13:00
     * 下午:13:00--17:00
     * 傍晚:17:00--19:00
     * 晚上:19:00--23:00
     * 深夜:23:00--3:00
     */
    public static String getTimeDivide(int time) {
        if (time >= 3 && time < 6) {
            return "凌晨";
        } else if (time >= 6 && time < 8) {
            return "早晨";
        } else if (time >= 8 && time < 11) {
            return "上午";
        } else if (time >= 11 && time < 13) {
            return "中午";
        } else if (time >= 13 && time < 17) {
            return "下午";
        } else if (time >= 17 && time < 19) {
            return "傍晚";
        } else if (time >= 19 && time < 23) {
            return "晚上";
        } else if (time >= 23 || time < 3) {
            return "深夜";
        }
        return null;
    }

    /**
     * @param mTextView
     * @param sendStr
     * @param receiveStr
     * @param commentStr {设置社区评论样式}
     */
    public static void SpannableStringSetting(TextView mTextView, String sendStr, String receiveStr, String commentStr) {
        SpannableString spannableString = null;
        if (!TextUtils.isEmpty(sendStr) && !TextUtils.isEmpty(receiveStr)) {//都不为空
            spannableString = new SpannableString(sendStr + "回复" + receiveStr + ":" + commentStr);
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#cc1744")), 0, sendStr.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#999999")), sendStr.length(), sendStr.length() + 2, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#cc1744")), sendStr.length() + 2, sendStr.length() + 2 + receiveStr.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#111111")), sendStr.length() + 2 + receiveStr.length(), spannableString.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        } else if (!TextUtils.isEmpty(sendStr)) {//发送者不为空
            spannableString = new SpannableString(sendStr + ":" + commentStr);
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#cc1744")), 0, sendStr.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#111111")), sendStr.length(), spannableString.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        }
        // 设置mTextView为可点击状态
        mTextView.setMovementMethod(LinkMovementMethod.getInstance());
        mTextView.setText(spannableString);
    }

    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {

        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { //如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
                && (codePoint <= 0x10FFFF));
    }

    /*表情过滤器*/
    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母、数字和汉字
        // String  regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";
        // 只允许汉字和.
        Pattern p = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 生成漂亮的颜色
     */
    public static int generateBeautifulColor() {
        Random random = new Random();
        //为了让生成的颜色不至于太黑或者太白，所以对3个颜色的值进行限定
        int red = random.nextInt(150) + 50;//50-200
        int green = random.nextInt(150) + 50;//50-200
        int blue = random.nextInt(150) + 50;//50-200
        return Color.rgb(red, green, blue);//使用r,g,b混合生成一种新的颜色
    }

    /*是否包含中文*/
    public static boolean isContainChinese(String str) {

        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /*是否包含特殊字符*/
    public static boolean isContainSpecialCharacter(String str) {

        Pattern p = Pattern.compile("[^a-zA-Z0-9\\u4E00-\\u9FA5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * {社区回复处理被回复者名称for单行显示hint}
     *
     * @param hint
     * @return 返回处理后的hint
     */
    public static String configHint(String hint) {
        String ret = hint;
        if (!TextUtils.isEmpty(hint)) {
            boolean containChinese = isContainChinese(hint);
            boolean containSpecialCharacter = isContainSpecialCharacter(hint);
            Log.i(TAG, "configHint: 包含中文？" + containChinese + ",包含特殊字符？" + containSpecialCharacter);
            if (containChinese) {//是中文截取前10,
                if (hint.length() >= 10) {
                    ret = hint.substring(0, 9) + "...";
                }
            } else if (containSpecialCharacter) {//是特殊字符截取前10
                if (hint.length() >= 10) {
                    ret = hint.substring(0, 6) + "...";
                }
            } else {//英文截取前20
                if (hint.length() >= 16) {
                    ret = hint.substring(0, 15) + "...";
                }
            }
        }
        Log.i(TAG, "configHint: ======处理后的hint文本======" + ret);
        return "回复：" + ret;
    }

    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 通过经纬度获取距离(单位：米)
     *
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return
     */
    public static double getMapDistance(double lat1, double lng1, double lat2,
                                        double lng2) {
        Log.i("AAA", "getDistance: =======进来了=======");
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        s = s * 1000;
        Log.i("AAA", "getDistance: 两者的距离：" + s);
        return s;
    }


    /**
     * 获取软件盘的高度
     */
    public static int getSupportSoftInputHeight(Activity activity) {
        Rect r = new Rect();
        /**
         * decorView是window中的最顶层view，可以从window中通过getDecorView获取到decorView。
         * 通过decorView获取到程序显示的区域，包括标题栏，但不包括状态栏。
         */
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
        //获取屏幕的高度
        int screenHeight = activity.getWindow().getDecorView().getRootView().getHeight();
        //计算软件盘的高度
        int softInputHeight = screenHeight - r.bottom;

        /**
         * 某些Android版本下，没有显示软键盘时减出来的高度总是144，而不是零，
         * 这是因为高度是包括了虚拟按键栏的(例如华为系列)，所以在API Level高于20时，
         * 我们需要减去底部虚拟按键栏的高度（如果有的话）
         */
        if (Build.VERSION.SDK_INT >= 20) {
            // When SDK Level >= 20 (Android L), the softInputHeight will contain the height of softButtonsBar (if has)
            softInputHeight = softInputHeight - getSoftButtonsBarHeight(activity);
        }


        return softInputHeight;
    }


    /**
     * 底部虚拟按键栏的高度
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static int getSoftButtonsBarHeight(Activity activity) {
        DisplayMetrics metrics = new DisplayMetrics();
        //这个方法获取可能不是真实屏幕的高度
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        //获取当前屏幕的真实高度
        activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight) {
            return realHeight - usableHeight;
        } else {
            return 0;
        }
    }

    /**
     * 根据路径获取文件名
     *
     * @return
     */
    public String getFileName(String pathandname) {
        int start = pathandname.lastIndexOf("/");
        int end = pathandname.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return pathandname.substring(start + 1, end);
        } else {
            return null;
        }
    }

    /**
     * 获取手机号码后四位
     *
     * @param mobile
     * @return
     */
    public static String getMobile(String mobile) {
        String mobile1 = SPUtils.getEditoString(SPUtils.SP_PHONE);
        String substring = mobile1.substring(mobile1.length() - 4, mobile1.length());
        return substring;
    }

    /**
     * 是否是华为
     */
    public static boolean isHUAWEI() {
        return android.os.Build.MANUFACTURER.equals("HUAWEI");
    }

    //获取是否存在虚拟键盘
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        try {
            Resources rs = context.getResources();
            int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
            if (id > 0) {
                hasNavigationBar = rs.getBoolean(id);
            }
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
        }
        return hasNavigationBar;
    }

    //获取虚拟按键的高度
    public static int getNavigationBarHeight(Context context) {
        int result = 0;
        if (checkDeviceHasNavigationBar(context)) {
            Resources res = context.getResources();
            int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = res.getDimensionPixelSize(resourceId);
            }
        }
        return result;
    }

    /**
     * 显示虚拟按键
     */
    public static void showBottomUIMenu(Activity activity) {
        //显示虚拟按键
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = activity.getWindow().getDecorView();
            v.setSystemUiVisibility(View.VISIBLE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = activity.getWindow().getDecorView();
            int uiOptions = View.STATUS_BAR_VISIBLE;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    public static void hideBottomUIMenu(Activity activity) {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = activity.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = activity.getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                    View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    /**
     * @return
     * @method
     * @description oss文件地址截取
     * @date: 2018/9/25 19:37
     * @author: ljp
     */
    public static String spitString(String objectKey) {
        String[] split = objectKey.split("\\/");
        StringBuffer buffer = new StringBuffer();
        buffer.append(split[3] + "/" + split[4]);
        //Log.i(TAG, "setSureRegister: -----------"+buffer);
        return buffer.toString();
    }
    /**
     * @return
     * @method
     * @description 系统版本号截取
     * @date: 2018/9/25 19:37
     * @author: ljp
     */
    public static String spitStringVersion(String objectKey) {
        String[] split = objectKey.split("\\.");
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < split.length; i++) {
            buffer.append(split[i]);
        }
        return buffer.toString();
    }

    /**
     * @return
     * @method
     * @description 获取语音介绍文件名
     * @date: 2018/9/25 19:37
     * @author: ljp
     */
    public static String getVoiceName(String objectKey) {
        String[] split = objectKey.split("\\/");
        StringBuffer buffer = new StringBuffer();
        buffer.append(split[1]);
        //Log.i(TAG, "setSureRegister: -----------"+buffer);
        return buffer.toString();
    }

    /**
     * @return
     * @method
     * @description 身高体重截取
     * @date: 2018/9/25 19:37
     * @author: ljp
     */
    public static String spitHeight(String height, int i) {
        String[] split = height.split(";");
        String str = split[i];
        // buffer.append(split[0]+"/"+split[4]);
        Log.i(TAG, "setSureRegister: -----------" + split.length);
        return str;
    }

    /**
     * @return
     * @method
     * @description 年龄截取
     * @date: 2018/11/17 15:07
     * @author: ljp
     */
    public static String getAge(String age) {
        String substring = age.substring(0, 4);
        String time = Utils.getStringTime(new Date());
        int i = (Integer.parseInt(time)) - (Integer.parseInt(substring));
        return String.valueOf(i);
    }

    /**
     * @return
     * @method
     * @description 截取图片地址
     * @date: 2018/9/25 19:37
     * @author: ljp
     */
    public static String[] spitPictureUrl(String url) {
        String[] split = url.split(",");
        String[] urls = new String[split.length];
        for (int i = 0; i < split.length; i++) {
            urls[i] = split[i];
        }
        // buffer.append(split[0]+"/"+split[4]);
        return urls;
    }

    /**
     * @return
     * @method
     * @description 会话列表个人信息截取
     * @date: 2018/9/25 19:37
     * @author: ljp
     */
    public static String[] spitInfo(String str) {
        String[] split = str.split(";");
        String[] urls = new String[split.length];
        for (int i = 0; i < split.length; i++) {
            urls[i] = split[i];
        }
        return urls;
    }

    public static String[] spitInfo(String str, String sign) {
        String[] split = str.split(sign);
        String[] urls = new String[split.length];
        for (int i = 0; i < split.length; i++) {
            urls[i] = split[i];
        }
        return urls;
    }

    /**
     * 解析asses文件夹下json文件
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    /**
     * @return
     * @method
     * @description 录音时间转换
     * @date: 2018/9/27 19:34
     * @author: ljp
     */
    public static String long2String(long time) {
        int sec = (int) time / 1000;
        int min = sec / 60;
        //sec %= 60;
        return sec + "";
    }

    public static String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(Long.valueOf(System.currentTimeMillis()));
    }

    /**
     * @return
     * @method
     * @description 手机号码*显示
     * @date: 2018/11/1 20:02
     * @author: ljp
     */
    public static String getPhoneNumber(String phoneNum) {
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(phoneNum) && phoneNum.length() > 6) {
            for (int i = 0; i < phoneNum.length(); i++) {
                char c = phoneNum.charAt(i);
                if (i >= 3 && i <= 6) {
                    sb.append('*');
                } else {
                    sb.append(c);
                }
            }
        }
        return sb.toString();
    }

    /**
     * @return
     * @method
     * @description 姓名
     * @date: 2018/11/1 20:02
     * @author: ljp
     */
    public static String getName(String phoneNum) {
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(phoneNum)) {
            for (int i = 0; i < phoneNum.length(); i++) {
                char c = phoneNum.charAt(i);
                if (i >= 1 && i <= phoneNum.length()) {
                    sb.append('*');
                } else {
                    sb.append(c);
                }
            }
        }
        return sb.toString();
    }

    /**
     * @return
     * @method
     * @description 经纬度转换
     * @date: 2018/9/25 19:37
     * @author: ljp
     */
    public static String spitLongString(String str) {
        String[] split = str.split("\\.");
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < split.length; i++) {
            buffer.append(split[i]);
        }
        //Log.i(TAG, "setSureRegister: -----------"+buffer);
        return buffer.toString();
    }
    /**
     * @return
     * @method
     * @description 经纬度保留小数点五位小数
     * @date: 2018/9/25 19:37
     * @author: ljp
     */
    public static String spitDoubleString(double value) {
         DecimalFormat df = new DecimalFormat("#.00000");
        return df.format(value);
    }
    // strTime要转换的string类型的时间，formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
    // HH时mm分ss秒，
    // strTime的时间格式必须要与formatType的时间格式相同
    public static Date stringToDate(String strTime, String formatType)
            throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        date = formatter.parse(strTime);
        return date;
    }

    // formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
    // data Date类型的时间
    public static String dateToString(Date data, String formatType) {
        return new SimpleDateFormat(formatType).format(data);
    }

    /**
     * 时间转化为聊天界面显示字符串
     *
     * @param timeStamp 单位为秒
     */
    public static String getChatTimeStr(long timeStamp,String format) {
        if (timeStamp == 0) return "";
        Calendar inputTime = Calendar.getInstance();
        inputTime.setTimeInMillis(timeStamp * 1000);
        Date currenTimeZone = inputTime.getTime();
        Calendar calendar = Calendar.getInstance();
        if (calendar.before(inputTime)) {
            //当前时间在输入时间之前
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy" + App.getContext().getResources().getString(R.string.time_year) + "MM" + App.getContext().getResources().getString(R.string.time_month) + "dd" + App.getContext().getResources().getString(R.string.time_day));
            return sdf.format(currenTimeZone);
        }
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        if (calendar.before(inputTime)) {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            return sdf.format(currenTimeZone);
        }
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        if (calendar.before(inputTime)) {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            return App.getContext().getResources().getString(R.string.time_yesterday) + " " + sdf.format(currenTimeZone);
        } else {
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.MONTH, Calendar.JANUARY);
            if (calendar.before(inputTime)) {
                SimpleDateFormat sdf = new SimpleDateFormat("M" + App.getContext().getResources().getString(R.string.time_month) + "d" + App.getContext().getResources().getString(R.string.time_day) + " HH:mm");
                return sdf.format(currenTimeZone);
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat(format);
                return sdf.format(currenTimeZone);
            }

        }
    }

    /**
     * 获取本地软件版本号名称
     */
    public static String getLocalVersionName(Context ctx) {
        String localVersion = "";
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionName;
            //LogUtil.d("TAG", "本软件的版本号。。" + localVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    /**
     * 根据毫秒返回时分秒
     *
     * @param time
     * @return
     */
    public static String getFormatHMS(long time) {
        time = time / 1000;//总秒数
        int s = (int) (time % 60);//秒
        int m = (int) ((time / 60)% 60);//分
        int h = (int) (time / 3600);//时
        //Log.i(TAG, "getFormatHMS: ----m----"+m);
        //Log.i(TAG, "getFormatHMS: -----h---"+h);
        if (h == 0) {
            return String.format("%02d:%02d", m, s);
        } else {
            return String.format("%02d:%02d:%02d", h, m, s);
        }
    }
    /**
     * 启动裁剪
     *
     * @param activity
     * @param cropBean
     * @param requestCode
     */
    public static void startCrop(Activity activity, CropBean cropBean, int requestCode) {
        if (cropBean == null) {
            Toast.makeText(activity, "参数对象为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (cropBean.dataUri == null) {
            Toast.makeText(activity, "请设置裁剪图片的Uri：dataUri", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent("com.android.camera.action.CROP");
        //配置一系列裁剪参数
        //intent.putExtra("outputX", cropBean.outputX);
        // intent.putExtra("outputY", cropBean.outputY);
        //intent.putExtra("scale", cropBean.scale);
        // intent.putExtra("aspectX", 0);
        //  intent.putExtra("aspectY", 0);
        intent.putExtra("outputFormat", cropBean.outputFormat);
        intent.putExtra("return-data", cropBean.isReturnData);

        //如果TargetSdkVersion >= 24
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //申请权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //将数据Uri转化成FileProvider的Uri
            File dataFile = new File(UriUtil.getPath(cropBean.dataUri));
            cropBean.dataUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".android7.fileprovider", dataFile);

            Log.i("mengyuanuri", "SDK>=24裁剪的Uri:" + cropBean.dataUri.getScheme() + ":" + cropBean.dataUri.getSchemeSpecificPart());
            Log.i("mengyuanuri", "SDK>=24裁剪保存的Uri:" + cropBean.saveUri.getScheme() + ":" + cropBean.saveUri.getSchemeSpecificPart());
        }
        //设置要裁剪的图片Uri
        intent.setDataAndType(cropBean.dataUri, "image/*");
        // 如果不需要返回Btimap，则需要指定图片保存的Uri
        if (!cropBean.isReturnData) {
            if (cropBean.saveUri == null) {
                Toast.makeText(activity, "请指定保存裁剪图片地址：saveUri", Toast.LENGTH_SHORT).show();
                return;
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, cropBean.saveUri);
        }

        activity.startActivityForResult(intent, requestCode);

    }

    /**
     * 纯字母
     *
     * @param data
     * @return
     */
    public static boolean isChar(String data) {
        for (int i = data.length(); --i >= 0; ) {
            char c = data.charAt(i);
            if (((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断服务是否开启
     *
     * @return
     */
    public static boolean isServiceRunning(Context context, String ServiceName) {
        if (("").equals(ServiceName) || ServiceName == null)
            return false;
        ActivityManager myManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager
                .getRunningServices(30);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString()
                    .equals(ServiceName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @return
     * @method
     * @description 获取渠道号
     * @date: 2018/12/17 15:05
     * @author: ljp
     */
    public static String getChannel(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo appInfo = pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            return appInfo.metaData.getString("UMENG_CHANNEL");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取application中指定的meta-data。本例中，调用方法时key就是UMENG_CHANNEL
     *
     * @return 如果没有获取成功(没有对应值 ， 或者异常)，则返回值为空
     */
    public static String getAppMetaData(Context ctx, String key) {
        if (ctx == null || TextUtils.isEmpty(key)) {
            return null;
        }
        String resultData = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        resultData = applicationInfo.metaData.getString(key);
                    }
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return resultData;
    }
}